package zd.cornermemory.fragment.record;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import zd.cornermemory.App;
import zd.cornermemory.R;
import zd.cornermemory.bean.CjMap;
import zd.cornermemory.db.Cj;
import zd.cornermemory.ui.AoDetailActivity;
import zd.cornermemory.ui.CjDetailActivity;
import zd.cornermemory.ui.CjPjDetailActivity;
import zd.cornermemory.utils.Statistics;

import static zd.cornermemory.utils.Statistics.timeToString;

/**
 * Created by zhud on 2019/4/29.
 */

public class StatisticsFragment extends Fragment implements View.OnClickListener{
    private List<Cj>  cjs;
    private TextView       zpj;
    private TextView       zpj_show;
    private TextView       min_text;
    private TextView       max_text;
    private TextView       group_text;
    private RelativeLayout max_layout,min_layout,pj_layout;
    private Cj minCj,maxCj;
    private int currentPos;
    private int mPosition;//传入详情页的

    private TextView mo3_show;
    private TextView ao5_show;
    private TextView ao12_show;

    private TextView min_mo3_show;
    private TextView min_ao5_show;
    private TextView min_ao12_show;

    private RelativeLayout mo3_layout;
    private RelativeLayout ao5_layout;
    private RelativeLayout ao12_layout;
    private RelativeLayout min_mo3_layout;
    private RelativeLayout min_ao5_layout;
    private RelativeLayout min_ao12_layout;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_cj_tj, container, false);
        initViews(view);
        initData();
        return view;
    }

    private void initViews(View v) {
        group_text = v.findViewById(R.id.group_text);
        group_text = v.findViewById(R.id.group_text);
        zpj = v.findViewById(R.id.zpj);
        zpj_show = v.findViewById(R.id.zpj_show);
        min_text = v.findViewById(R.id.min);
        max_text = v.findViewById(R.id.max);
        min_layout = v.findViewById(R.id.min_layout);
        max_layout = v.findViewById(R.id.max_layout);
        pj_layout = v.findViewById(R.id.pj_layout);

        mo3_show = v.findViewById(R.id.mo3_show);
        ao5_show = v.findViewById(R.id.ao5_show);
        ao12_show = v.findViewById(R.id.ao12_show);
        min_mo3_show = v.findViewById(R.id.min_mo3_show);
        min_ao5_show = v.findViewById(R.id.min_ao5_show);
        min_ao12_show = v.findViewById(R.id.min_ao12_show);

        mo3_layout = v.findViewById(R.id.mo3_layout);
        ao5_layout = v.findViewById(R.id.ao5_layout);
        ao12_layout = v.findViewById(R.id.ao12_layout);
        min_mo3_layout = v.findViewById(R.id.min_mo3_layout);
        min_ao5_layout = v.findViewById(R.id.min_ao5_layout);
        min_ao12_layout = v.findViewById(R.id.min_ao12_layout);

        min_layout.setOnClickListener(this);
        max_layout.setOnClickListener(this);
        pj_layout.setOnClickListener(this);

        mo3_layout.setOnClickListener(this);
        ao5_layout.setOnClickListener(this);
        ao12_layout.setOnClickListener(this);
        min_mo3_layout.setOnClickListener(this);
        min_ao5_layout.setOnClickListener(this);
        min_ao12_layout.setOnClickListener(this);
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            cjs = new ArrayList<>();
            currentPos = getActivity().getIntent().getExtras().getInt("currentPos");
            String[] scr = getResources().getStringArray(R.array.scr);
            group_text.setText(scr[currentPos]);
            List<Cj> temp  = App.getInstance().getAllCjMap().get(currentPos);
            if (temp == null) {
                temp = new ArrayList<>();
            }
            cjs.addAll(temp);
            Collections.sort(cjs, new Comparator<Cj>() {
                @Override
                public int compare(Cj cj, Cj t1) {
                    return (int)(t1.getId()-cj.getId());
                }
            });
            setMinMax();//7ms
            setMo();//1ms
            setMinMo();//500ms
        }
    };

    public void initData() {
        mHandler.sendEmptyMessage(3);
    }

    private int mMinPosition;
    private int mMaxPosition;

    private void setMinMax() {
        List<Cj> tempList = new ArrayList<>();
        List<Cj> cjList = new ArrayList<>();
        tempList.addAll(cjs);
        Collections.sort(tempList, new Comparator<Cj>() {
            @Override
            public int compare(Cj cj, Cj t1) {
                return (int)(cj.getId()-t1.getId());
            }
        });
        for (Cj cj : tempList) {
            if (cj.getStatus() != 2) {
                cjList.add(cj);
            }
        }
        zpj.setText(getString(R.string.avg_all)+getString(R.string.left_k)+cjList.size()+"/"+cjs.size()+getString(R.string.right_k));
        long avg = 0;
        for (Cj cj : cjList) {
            avg += cj.getSingTime();
        }
        if (avg == 0) {
            zpj_show.setText("N/A");
            min_text.setText("N/A");
            max_text.setText("N/A");
            minCj = null;
            maxCj = null;
        }else{
            double a = avg/cjList.size();
            avg = Math.round(a);
            String avgStr = timeToString((int) avg);
            zpj_show.setText(avgStr);
            minCj = Collections.min(cjList);
            long minId = minCj.getId();
            for(int i=0;i<cjs.size();i++) {
                long currentId = cjs.get(i).getId();
                if (currentId == minId) {
                    mMinPosition = i;
                    break;
                }
            }

            maxCj = Collections.max(cjList);
            long maxId = maxCj.getId();
            for(int i=0;i<cjs.size();i++) {
                long currentId  = cjs.get(i).getId();
                if (currentId == maxId) {
                    mMaxPosition = i;
                    break;
                }
            }
            String minStr = Statistics.timeToString(minCj.getSingTime().intValue());
            if (minCj.getStatus() == 1) {
                minStr += "+";
            }

            String maxStr = Statistics.timeToString(maxCj.getSingTime().intValue());
            if (maxCj.getStatus() == 1) {
                maxStr += "+";
            }

            min_text.setText(minStr);
            max_text.setText(maxStr);
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.min_layout:
                if (minCj == null) {
                    return;
                }
                gotoDetail(true);
                break;
            case R.id.max_layout:
                if (maxCj == null) {
                    return;
                }
                gotoDetail(false);
                break;
            case R.id.pj_layout:
                if (minCj == null) {
                    return;
                }
                gotoPj();
                break;

            case R.id.mo3_layout:
                if (mo3List.size() != 0) {
                    gotoAoDetail(getString(R.string.current_3),mo3List);
                }
                break;
            case R.id.ao5_layout:
                if (ao5List.size() != 0) {
                    gotoAoDetail(getString(R.string.current_5),ao5List);
                }
                break;
            case R.id.ao12_layout:
                if (ao12List.size() != 0) {
                    gotoAoDetail(getString(R.string.current_12),ao12List);
                }
                break;
            case R.id.min_mo3_layout:
                if (minMo3Lists.size() != 0) {
                    gotoAoDetail(getString(R.string.best_3),minMo3Lists);
                }
                break;
            case R.id.min_ao5_layout:
                if (minAo5Lists.size() != 0) {
                    gotoAoDetail(getString(R.string.best_5),minAo5Lists);
                }
                break;
            case R.id.min_ao12_layout:
                if (minAo12Lists.size() != 0) {
                    gotoAoDetail(getString(R.string.best_12),minAo12Lists);
                }
                break;
        }
    }

    private void gotoAoDetail(String titleStr,List<Cj> cjs) {
        Intent intent = new Intent(getActivity(), AoDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("titleStr",titleStr);
        ArrayList<Cj> arrayList = new ArrayList<>();
        for (Cj cj : cjs) {
            arrayList.add(cj);
        }
        bundle.putSerializable("cj",arrayList);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void gotoDetail(boolean isMin) {
        Intent intent = new Intent(getActivity(), CjDetailActivity.class);
        Bundle bundle = new Bundle();
        mPosition = isMin?mMinPosition:mMaxPosition;
        bundle.putSerializable("bean",cjs.get(mPosition));
        bundle.putInt("position",cjs.size()-mPosition);
        bundle.putInt("currentPos",currentPos);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void gotoPj() {
        Intent intent = new Intent(getActivity(), CjPjDetailActivity.class);
        intent.putExtra("currentPos", currentPos);
        startActivity(intent);
    }

    ArrayList<CjMap> mo3Map  = new ArrayList<>();//平均值，列表
    ArrayList<CjMap> ao5Map  = new ArrayList<>();//平均值，列表
    ArrayList<CjMap> ao12Map = new ArrayList<>();//平均值，列表

    //最好
    private void setMinMo() {
        mo3Map.clear();
        ao12Map.clear();
        ao5Map.clear();
        min_mo3_show.setText(DNF);
        min_ao5_show.setText(DNF);
        min_ao12_show.setText(DNF);
        if (cjs.size() < 12) {
            ao12Map.clear();
            min_ao12_show.setText(NA);
        }

        if (cjs.size() < 5) {
            ao5Map.clear();
            min_ao5_show.setText(NA);
        }

        if (cjs.size() < 3) {
            mo3Map.clear();
            min_mo3_show.setText(NA);
        }
        split(cjs,3);
        split(cjs,5);
        split(cjs,12);

        if (mo3Map.size() > 0) {
            String minMo3Str = getString(mo3Map,3);
            min_mo3_show.setText(minMo3Str);
        }

        if (ao5Map.size()>0) {
            String minAo5Str = getString(ao5Map,5);
            min_ao5_show.setText(minAo5Str);
        }

        if (ao12Map.size()>0) {
            String minAo12Str = getString(ao12Map,12);
            min_ao12_show.setText(minAo12Str);
        }

    }

    private String getString(List<CjMap> map,int x) {
        CjMap cmap = Collections.min(map);
        if (cmap != null) {
            switch (x) {
                case 3:
                    minMo3Lists = cmap.getCjList();
                    break;
                case 5:
                    minAo5Lists= cmap.getCjList();
                    break;
                case 12:
                    minAo12Lists= cmap.getCjList();
                    break;
            }
        }

        return getAvgStr(cmap==null?null:cmap.getCjList());
    }


    private String getAvgStr(List<Cj> cjList) {
        if (cjList == null || cjList.size() == 0) {
            return DNF;
        }
        List<Cj> ao = new ArrayList<>();
        Cj minCj = null;
        Cj maxCj = null;
        for (Cj cj : cjList) {
            if (cj.getStatus() != 2) {
                ao.add(cj);
            }else{
                maxCj = cj;
            }

        }

        if (maxCj != null) {
            minCj = Collections.min(ao);
            ao.remove(minCj);
        }else{
            minCj = Collections.min(cjList);
            maxCj = Collections.max(cjList);
            if (cjList.size() != 3) {
                ao.remove(minCj);
                ao.remove(maxCj);
            }

        }

        long avg = 0;
        for (Cj cj : ao) {
            avg += cj.getSingTime();
        }
        double a = avg/ao.size();
        avg = Math.round(a);
        String avgStr = timeToString((int) avg);
        return avgStr;
    }

    private void split(List<Cj> list, int len) {
        if (list == null || list.size() == 0 || len < 1) {
            return;
        }
        //传入集合长度
        int size = list.size();
        for (int i = 0; i < size; i++) {
            if (i > (size - len)) {
                break;
            }
            List<Cj> subList = list.subList(i, (i + len) > size ? size : i + len);
            int avg = getAvgInt(subList);
            if (avg != 0) {
                if (len == 3) {
                    if (mo3Map.size() == 0) {
                        mo3Map.add(new CjMap(avg, subList));
                    }else{
                        int a = mo3Map.get(mo3Map.size()-1).getAvg();
                        if (avg < a) {
                            mo3Map.add(new CjMap(avg, subList));
                        }
                    }

                } else if (len == 5) {
                    if (ao5Map.size() == 0) {
                        ao5Map.add(new CjMap(avg, subList));
                    }else{
                        int a = ao5Map.get(ao5Map.size()-1).getAvg();
                        if (avg < a) {
                            ao5Map.add(new CjMap(avg, subList));
                        }
                    }

                } else if (len == 12) {
                    if (ao12Map.size() == 0) {
                        ao12Map.add(new CjMap(avg, subList));
                    }else{
                        int a = ao12Map.get(ao12Map.size()-1).getAvg();
                        if (avg < a) {
                            ao12Map.add(new CjMap(avg, subList));
                        }
                    }
                }
            }

        }
    }

    private String NA = "N/A";
    private String DNF = "DNF";
    private void setMo(){
        mo3(cjs);
        ao5(cjs);
        ao12(cjs);
    }

    private void mo3(List<Cj> cjList) {
        if (cjList.size() < 3) {
            mo3_show.setText(NA);
            return;
        }
        mo3List.clear();

        long timeCount = 0;//计算当前mo3
        int count = 0;
        for(int i = 0;i<3;i++) {
            Cj cj = cjList.get(i);
            if (cj.getStatus() != 2) {
                timeCount+=cj.getSingTime();
                count++;
            }
            mo3List.add(cj);
        }
        if (count == 3) {//有mo3
            double avg = Math.round(timeCount/3);
            String avgStr = Statistics.timeToString((int) avg);
            mo3_show.setText(avgStr);
        }else{
//            mo3List.clear();
            mo3_show.setText(DNF);
        }
    }

    private void ao5(List<Cj> cjList) {
        if (cjList.size() < 5) {
            ao5_show.setText(NA);
            return;
        }
        ao5List.clear();
        int count = 0;
        Cj dnfCj = null;
        for(int i = 0;i<5;i++) {
            Cj cj = cjList.get(i);
            if (cj.getStatus() == 2) {
                count++;
                dnfCj = cj;
            }
            ao5List.add(cj);
        }

        if (count >= 2) {//DNF
//            ao5List.clear();
            ao5_show.setText(DNF);
        }else if(count == 1){
            List<Cj> ao5 = new ArrayList<>();
            for (Cj cj : ao5List) {
                if (cj.getId() != dnfCj.getId()) {
                    ao5.add(cj);
                }
            }
            Cj min = Collections.min(ao5);
            ao5.remove(min);
            long time = 0;
            for (Cj cj : ao5) {
                time += cj.getSingTime();
            }
            double avg = Math.round(time / 3);
            String avgStr = Statistics.timeToString((int) avg);
            ao5_show.setText(avgStr);
        }else {
            List<Cj> ao5 = new ArrayList<>();
            for (Cj cj : ao5List) {
                ao5.add(cj);
            }
            Cj min = Collections.min(ao5);
            Cj max = Collections.max(ao5);
            ao5.remove(min);
            ao5.remove(max);
            long time = 0;
            for (Cj cj : ao5) {
                time += cj.getSingTime();
            }
            double avg = Math.round(time / 3);
            String avgStr = Statistics.timeToString((int) avg);
            ao5_show.setText(avgStr);
        }
    }

    private void ao12(List<Cj> cjList) {
        if (cjList.size() < 12) {
            ao12_show.setText(NA);
            return;
        }
        ao12List.clear();
        int count = 0;
        Cj dnfCj = null;
        for(int i = 0;i<12;i++) {
            Cj cj = cjList.get(i);
            if (cj.getStatus() == 2) {
                count++;
                dnfCj = cj;
            }
            ao12List.add(cj);
        }

        if (count >= 2) {//DNF
//            ao12List.clear();
            ao12_show.setText(DNF);
        }else if(count == 1){
            List<Cj> ao12 = new ArrayList<>();
            for (Cj cj : ao12List) {
                if (cj.getId() != dnfCj.getId()) {
                    ao12.add(cj);
                }
            }
            Cj min = Collections.min(ao12);
            ao12.remove(min);
            long time = 0;
            for (Cj cj : ao12) {
                time += cj.getSingTime();
            }
            double avg = Math.round(time / 10);
            String avgStr = Statistics.timeToString((int) avg);
            ao12_show.setText(avgStr);
        }else {
            List<Cj> ao12 = new ArrayList<>();
            for (Cj cj : ao12List) {
                ao12.add(cj);
            }
            Cj min = Collections.min(ao12);
            Cj max = Collections.max(ao12);
            ao12.remove(min);
            ao12.remove(max);
            long time = 0;
            for (Cj cj : ao12) {
                time += cj.getSingTime();
            }
            double avg = Math.round(time / 10);
            String avgStr = Statistics.timeToString((int) avg);
            ao12_show.setText(avgStr);
        }
    }

    private List<Cj> mo3List = new ArrayList<>();
    private List<Cj> ao5List = new ArrayList<>();
    private List<Cj> ao12List = new ArrayList<>();

    private List<Cj> minMo3Lists = new ArrayList<>();
    private List<Cj> minAo5Lists = new ArrayList<>();
    private List<Cj> minAo12Lists = new ArrayList<>();

    private int getAvgInt(List<Cj> cjList) {
        List<Cj> tempList = new ArrayList<>();
        long timeCount = 0;//
        int dnfCount = 0;
        Cj max = null;
        for(int i = 0;i<cjList.size();i++) {
            Cj cj = cjList.get(i);
            if (cj.getStatus() == 2) {
                dnfCount++;
                max = cj;
            }
            timeCount+=cj.getSingTime();
            tempList.add(cj);
        }

        if (cjList.size() == 3) {
            if (dnfCount > 0) {
                return 0;
            }else {
                double avg = Math.round(timeCount/cjList.size());
                return (int)avg;
            }
        }else {
            if (dnfCount == 0) {
                Cj min = Collections.min(tempList);
                max = Collections.max(tempList);
                tempList.remove(min);
                tempList.remove(max);
                long time = 0;
                for (Cj c : tempList) {
                    time += c.getSingTime();
                }
                double avg = Math.round(time/tempList.size());
                return (int)avg;
            } else if (dnfCount == 1) {
                tempList.remove(max);
                Cj min = Collections.min(tempList);
                tempList.remove(min);
                long time = 0;
                for (Cj c : tempList) {
                    time += c.getSingTime();
                }
                double avg = Math.round(time/tempList.size());
                return (int)avg;
            }else{
                return 0;
            }
        }

    }

}
